<template>
  <!-- 表格 -->
  <div class="table-box">
    <template v-if="selectObj.id">
      <!-- 提示 -->
      <div class="hint-box">
        <svg-icon
          icon-class="tishi_icon"
        />【不重复】当天未标记自动顺延到第二天；【每周重复】需要选择星期
      </div>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        highlight-current-row
        style="width: 100%"
        @row-click="edidBtn"
      >
        <el-table-column width="35">
          <!-- 状态 -->
          <template :slot-scope="scope">
            <svg-icon icon-class="ing_icon" />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="任务"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="时间" show-overflow-tooltip>
          <template slot-scope="scope">
            <p>{{ getTimeTxt(scope.row) }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="repeatDays" label="重复" show-overflow-tooltip>
          <template slot-scope="scope">
            <p>{{ getRepeatDays(scope.row) }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="userList" label="执行人" show-overflow-tooltip>
          <template slot-scope="scope">
            <!-- <p>{{ getUserListName(scope.row) || "--" }}</p> -->
            <p>{{ scope.row.principalName || "--" }}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="90"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div class="hineShow">
              <p
                class="hineShowP"
                :class="getStatusTxt(scope.row) == '未标记' ? 'isRed' : ''"
              >
                {{ getStatusTxt(scope.row) }}<i class="el-icon-arrow-down"></i>
              </p>
              <el-select
                v-model="scope.row.status"
                size="small"
                placeholder="请选择"
                class="isHine"
                @change="changeStatus(scope.row)"
                v-if="changeStatusType(scope.row)"
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="40">
          <template slot-scope="scope">
            <el-popover
              placement="bottom"
              width="50"
              trigger="hover"
              popper-class="tableFn-btn"
            >
              <div class="popover-btn">
                <!-- <el-button>群聊</el-button>
                <el-button>语音</el-button>
                <el-button>视频</el-button> -->
                 <el-button
                  @click="editDisplay(scope.row)"
                 
                  >隐藏</el-button
                >
                <el-button
                  @click="edidBtn(scope.row)"
                  v-if="scope.row.createBy == $store.state.user.userId"
                  >编辑</el-button
                >
                <el-button
                  @click="removeBtn(scope.row)"
                  v-if="scope.row.createBy == $store.state.user.userId"
                  >删除</el-button
                >
              </div>
              <p class="edit_more" slot="reference">
                <i class="el-icon-more"></i>
              </p>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>

      <!-- 创建任务按钮 -->
      <div class="addTask">
        <!-- <svg-icon icon-class="addTask" @click="addBtn" /> -->
        <el-button class="taskNum" @click="addBtn"
          ><i class="el-icon-plus"></i>添加任务({{ finished.length }}/{{
            tableData.length
          }})</el-button
        >
      </div>
    </template>

    <!-- 无数据 -->
    <div class="noData-box" v-else>
      <img src="~@/assets/images/wjg_img@2x.png" alt="" />
      <p>当前未选择目标</p>
    </div>

    <!-- 创建任务弹框  -->
    <el-drawer
      :title="editObj.id ? '编辑任务' : '创建任务'"
      size="40%"
      :visible.sync="addTaskDrawer"
      @close="addTaskClose"
      class="addTaskClass"
    >
      <AddTask
        ref="addTask"
        :selectObj="selectObj"
        :editObj="editObj"
        @reqOrClose="reqOrClose"
        @drawerBottom="drawerBottom"
      ></AddTask>
    </el-drawer>
  </div>
</template>

<script>
import {
  getServiceActionTaskListApi,
  removeServiceActionTaskApi,
  updateStatusActionTaskApi,
  updateTodayStatusApi,
  taskDisplayApi
} from "@/BMViews/api/service/actionTask.js";
import {
  timestampToTime,
  getTimeFormat,
  TurnChinese,
} from "@/wss/utils/wss.js";
import AddTask from "./addTask.vue";
import { transferTime } from "@/wss/utils/wss.js";

export default {
  name: "table",
  components: { AddTask },
  props: {
    //当前选中的一条目标数据
    selectObj: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      tableData: [], //表格数据
      // 选择框
      statusList: [
        {
          value: "-1",
          label: "取消",
        },
        {
          value: "1",
          label: "未完成",
        },
        {
          value: "2",
          label: "完成",
        },
      ],
      statusValue: 0, //选择的值

      addTaskDrawer: false, //创建任务弹出框
      editObj: {}, //当前编辑的这一条数据
      finished: [], //已完成的任务数
    };
  },
  mounted() {},
  watch: {
    // 监听选择的这个目标
    selectObj: {
      deep: true,
      handler() {
        this.getServiceActionTaskList(); // 查询当前选择的任务列表
      },
    },
  },
  methods: {
    // 查询当前选择的任务列表
    async getServiceActionTaskList() {
      let targetId = this.selectObj.id;
      let result = await getServiceActionTaskListApi({ targetId });
      console.log("result:任务列表", result);
      if (result.code == 200) {
        this.tableData = result.rows;
        this.finished = result.rows.filter((v) => v.status == "2"); // 获取已完成的任务
        this.$bus.$emit("refLeftList"); // 刷新左边目标列表
        console.log("tableData:", this.tableData);
        console.log("finished:", this.finished);
      }
    },

    // 刷新列表并且关闭弹出框
    reqOrClose() {
      this.getServiceActionTaskList(); // 查询当前选择的任务列表
      this.addTaskDrawer = false; //关闭弹出框
    },

    // 获取怎样的重复
    getRepeatDays(row) {
      if (row.repeatDays.includes("；")) {
        // 是每周重复
        let arr = row.repeatDays.split("；");
        let str = [];
        // TurnChinese
        arr.forEach((item) => {
          str.push(`星期${TurnChinese(item)}`);
        });
        return str.join(",");
      } else {
        // 不是每周重复
        const stateMap = {
          "-1": "不重复",
          0: "工作日重复",
          9: "每天重复",
        };
        return stateMap[row.repeatDays];
      }
    },

    // 获取状态的名字
    getStatusTxt(row) {
      // 重复以todaystatus为主
      if (row.repeatDays == -1) {
        if (row.status) {
          // 有状态数据
          const stateMap = {
            "-1": "取消",
            1: "未完成",
            2: "完成",
          };
          return stateMap[row.status];
        } else {
          // 开始时间还没到就是未到期，开始时间到了就是未标记(红色的字)
          if (!row.startDay) return;
          let start = timestampToTime(row.startDay) + row.startTime + ":00";
          let startDate = new Date(start).getTime();
          let nowDate = new Date().getTime();
          // console.log(startDate,nowDate,'获取状态的名字获取状态的名字');
          // 开始时间大于当前时间
          if (startDate > nowDate) {
            return "未到期";
          } else {
            return "未标记";
          }
        }
      } else {
        // ---------已到期的情况---------
        if(row.finalTime){
          let finalTime = new Date(row.finalTime).getTime()
          let now = new Date().getTime()
          if(now>finalTime){
            return "已到期"
          }
        }
        // ---------已到期的情况---------end
        if (row.todayStatus || row.status) {
          // 有状态数据
          const stateMap = {
            "-1": "取消",
            1: "未完成",
            2: "完成",
          };
          return stateMap[row.todayStatus || row.status];
        } else {
          // 开始时间还没到就是未到期，开始时间到了就是未标记(红色的字)
          if (!row.startDay) return;
          let start = timestampToTime(row.startDay) + row.startTime + ":00";
          let startDate = new Date(start).getTime();
          let nowDate = new Date().getTime();
          // console.log(startDate,nowDate,'获取状态的名字获取状态的名字');
          // 开始时间大于当前时间
          if (startDate > nowDate) {
            return "未到期";
          } else {
            return "未标记";
          }
        }
      }
    },
    // ---------判断当前任务是否已有状态
  changeStatusType(e){
    let userId = this.$store.state.user.userId
    // 判断是创建的人、指派的人、目标创建人可以编辑其他的都不行
    if(e.createBy==userId || e.principal==userId || e.createBy==userId){
      return true
    }else{
      return false
    }
    // if(e.repeatDays == -1 ){
    //     return e.status ? false : true
    // }else{
    //   return e.todayStatus ? true : false
    // }
  },  
    // 修改状态
    async changeStatus(row) {
      // console.log(row, "选择的结果");

      if (row.repeatDays == -1) {
        // 不重复修改状态
        await this.updateStatusActionTask(row); // 修改任务状态
        await this.updateTodayStatusFn(row); // 修改当天任务状态
      } else {
        // 重复的
        if (row.status == -1) {
          //取消状态
          await this.updateStatusActionTask(row); // 编辑一个任务的接口
          await this.updateTodayStatusFn(row); // 修改当天任务状态
        } else {
          await this.updateTodayStatusFn(row); // 修改当天任务状态
        }
      }
      this.getServiceActionTaskList(); // 查询当前选择的任务列表
      this.$bus.$emit("refLeftList"); // 刷新左边目标列表
      this.$message({ message: "编辑成功", type: "success" });
    },

    // 修改当天的任务状态接口
    async updateTodayStatusFn(row) {
      // --------------------传递修改状态参数的接口--------------------
      let date = new Date();
      let data = {
        status: row.status, //状态值
        // todayStatus: this.statusList[e.detail.value].value, //状态值
        targetId: row.targetId, //目标id
        taskId: row.id, //任务id
        taskDate: transferTime(date), //编辑的任务时间 没有传就用当天时间
      };
      console.log(data, "传入数据");
      let res = await updateTodayStatusApi([data]);
    },

    // 修改任务状态的接口
    async updateStatusActionTask(row) {
      let result = await updateStatusActionTaskApi([row]);
    },

    // 获取参与者
    getUserListName(row) {
      let userName = [];
      row.userList.forEach((item) => {
        // 过滤出已接受的
        if (item.userId == this.$store.state.user.userId) {
          userName.push("我");
        } else {
          userName.push(item.name);
        }
      });
      return userName.join(",");
    },

    // 获取时间
    getTimeTxt(row) {
      if (!row.startDay) return;
      let startDay = getTimeFormat(timestampToTime(row.startDay));
      if (!row.endDay) return;
      let endDay = getTimeFormat(timestampToTime(row.endDay));
      if (startDay == endDay) {
        return `${startDay} ${row.startTime}~${row.endTime}`;
      } else {
        return `${startDay} ${row.startTime}~${endDay} ${row.endTime}`;
      }
    },
      //点击隐藏按钮 
   async editDisplay(row){
      
      let id = this.$store.state.user.userId
      let index =  row.userList.findIndex(item=>{
        return item.userId == id
      })
      let argument = {
        id:row.id,
        display:!row.userList[index].display
      }
      const res = await taskDisplayApi(argument)
      if(res.code == 200){
         this.$message({message: res.msg, type: 'success'});
        //  删掉当前隐藏的list
         this.tableData.forEach((item,index) =>{ 
              if(item.id == row.id){
                  this.tableData.splice(index,1)
              }
         })
      }
    },
    // 点击编辑按钮
    edidBtn(row) {
      console.log("row:", row);
      // 不是自己创建的不能编辑
      // if (row.createBy != this.$store.state.user.userId) return;
      this.editObj = row;
      this.addTaskDrawer = true; //打开弹出框
    },

    // 点击添加按钮
    async addBtn() {
      this.editObj = {};
      this.addTaskDrawer = true; //打开弹出框
      // 点开默认指派给自己
      await this.$nextTick();
      this.$refs.addTask.form.principal = this.$store.state.user.userId;
    },

    // 抽屉关闭的时候
    addTaskClose() {
      this.editObj = {}; //清空当前编辑的这一条数据
    },

    // 点击删除的按钮
    removeBtn(row) {
      this.$confirm("确认删除该任务？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.removeServiceActionTask(row.id);
        })
        .catch(() => {});
    },

    // 删除任务的接口
    async removeServiceActionTask(id) {
      let result = await removeServiceActionTaskApi({ id });
      if (result.code == 200) {
        this.getServiceActionTaskList(); // 查询当前选择的任务列表
        this.$bus.$emit("refLeftList"); // 刷新左边目标列表
        this.$message({ message: result.msg, type: "success" });
      }
    },

    // 弹出的抽屉滚动到底部
    drawerBottom() {
      this.$nextTick(() => {
        var container = this.$el.querySelector(
          ".addTaskClass .el-drawer__body"
        );
        container.scrollTop = container.scrollHeight;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.table-box {
  // 提示
  .hint-box {
    font-size: 12px;
    font-weight: 400;
    color: #999999;
    margin: 10px 0 20px 0;
    svg {
      font-size: 16px;
    }
  }
  .el-select {
    ::v-deep .el-input__inner {
      border: 0;
      padding: 0;
      background-color: transparent;
    }
  }
  .isHine {
    opacity: 0;
  }
  .isRed {
    ::v-deep .el-input__inner {
      color: #ff0000;
    }
  }
  .el-table {
    p {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
    }
    .isRed {
      color: #ff0000;
    }
  }
}
// 隐藏选择器的状态
.hineShow {
  position: relative;
  min-height: 32px;
  .hineShowP {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    i {
      padding-left: 5px;
    }
  }
}

// 更多编辑按钮
.edit_more {
  cursor: pointer;
  opacity: 0.5;
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
}
.popover-btn {
  .el-button {
    width: 100%;
    padding: 6px 0px;
    margin: 0;
    border: 0;
    &:hover {
      color: #fa7c21;
      background-color: #fff4eb;
    }
    &:focus {
      color: #fa7c21;
      background-color: #fff4eb;
    }
  }
}
// 修改按钮的默认颜色
.el-button:hover,
.el-button:focus {
  color: #fa7c21;
}
// 创建任务按钮
.addTask {
  // position: absolute;
  // right: 30px;
  // bottom: 30px;
  // margin: 15px 0;
  // 底部创建任务
  .taskNum {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #f8f8f8;
    border: 0;
    border-top: 1px solid #ecedf0;
    padding: 15px;
    z-index: 99;
  }
  // svg {
  //   font-size: 45px;
  //   cursor: pointer;
  // }
}

::v-deep .el-table {
  border-top: 1px solid #efefef;
  margin-bottom: 80px;
}
::v-deep .el-table .cell {
  font-size: 13px;
  color: #333333;
}
::v-deep .el-table th > .cell {
  font-weight: normal;
  color: #909aaa;
}
::v-deep .el-table .el-table__header-wrapper th,
.el-table .el-table__fixed-header-wrapper th {
  background-color: #fff;
}
</style>
<style scoped>
.table-box p {
  padding: 0;
  margin: 0;
}
.table-box >>> .el-table th.is-leaf,
.table-box >>> .el-table td {
  border-bottom: 1px solid #efefef;
}
.table-box >>> .el-table__header-wrapper tbody td,
.table-box >>> .el-table__footer-wrapper tbody td {
  background-color: #fff;
  border-bottom: 0;
}

/* 抽屉样式 */
::v-deep .el-drawer__header {
  border-bottom: 1px solid #efefef;
  padding-bottom: 15px;
  margin-bottom: 20px;
}
::v-deep .el-drawer__header > span {
  font-size: 18px;
  font-weight: 400;
  color: #2e3f5e;
  padding-left: 20px;
  background: url("~@/wss/assets/image/icon/cardLeft.png") left center no-repeat;
  background-size: 7px;
}

/* 无数据 */
.noData-box {
  text-align: center;
  margin-top: 50px;
}
.noData-box img {
  width: 30%;
}
.noData-box > p {
  font-size: 12px;
  font-weight: 400;
  color: #858a91;
  margin-top: 30px;
}
</style>
<style>
.tableFn-btn {
  min-width: 60px;
  padding: 10px 0;
}
</style>
